import { useState } from 'react'
import { Modal, Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import './index.css'
// 使用本地 mock 登录
import { mockLogin } from '../../mock/users'
import { useDispatch } from 'react-redux'
import { loginSuccess } from '../../store/userSlice'

interface LoginModalProps {
	visible: boolean
	onClose: () => void
	onSuccess?: () => void
}
interface LoginFormValues {
	username: string
	password: string
}
const LoginModal = ({ visible, onClose }: LoginModalProps) => {
	const [form] = Form.useForm<LoginFormValues>()
	const [errorMsg, setErrorMsg] = useState('')
	const dispatch = useDispatch()
	
	const handleSubmit = async (values: LoginFormValues) => {
		try {
			const res = await mockLogin(values.username, values.password)
			console.log('mock login:', res)
			const code = res?.data?.code
			if (code === 200 || code === 0) {
				const payload = res?.data?.data
				if (!payload) {
					setErrorMsg(res?.data?.message || '登录响应异常')
					message.error(res?.data?.message || '登录响应异常')
					return
				}
				// 登录成功，将数据存入Redux
				dispatch(loginSuccess({
					accessToken: payload.accessToken,
					refreshToken: payload.refreshToken,
					userInfo: payload.userInfo
				}))
				message.success('登录成功')
				onClose() // 关闭登录框
				// 如果父组件提供了onSuccess回调，则调用它
				// if (onSuccess) onSuccess()
			}
			else {
				setErrorMsg(res.data.message || '登录失败，请重新登录')
				message.error('登录失败请重新登录')
			}
		} catch (error) {
			console.error('登录请求失败:', error)
			setErrorMsg('登录请求失败，请稍后再试')
			message.error('登录请求失败，请稍后再试')
		}
	}
	return (
		<>
			<Modal
				title=""
				open={visible}
				onCancel={() => {
					form.resetFields()
					setErrorMsg('')
					onClose()
				}}
				footer={null}
				maskClosable
				width={420}
				centered
				className="login-modal-advanced"
				styles={{
					mask: {
						backdropFilter: 'blur(8px)',
						backgroundColor: 'rgba(0, 0, 0, 0.4)'
					}
				}}
			>
				{/* 自定义标题区域 */}
				<div className="login-header">
					<div className="login-title">
						<h2>欢迎回来</h2>
						<p>请登录您的账户</p>
					</div>
				</div>
				<Form form={form} layout="vertical" onFinish={handleSubmit} autoComplete="off" className="login-form">
					{errorMsg ? (
						<div className="error-message">
							<span className="error-icon">⚠️</span>
							{errorMsg}
						</div>
					) : null}
					<Form.Item
						name="username"
						label="用户名"
						rules={[
							{ required: true, message: '用户名不能为空' },
						]}
					>
						<Input
							prefix={<UserOutlined className="input-icon" />}
							placeholder="请输入用户名"
							className="custom-input"
						/>
					</Form.Item>
					<Form.Item
						name="password"
						label="密码"
						rules={[
							{ required: true, message: '密码不能为空' },
							{ min: 5, message: '密码长度至少为 5 个字符' },
						]}
					>
						<Input.Password
							prefix={<LockOutlined className="input-icon" />}
							placeholder="请输入密码"
							className="custom-input"
						/>
					</Form.Item>
					<Form.Item>
						<Button
							type="primary"
							htmlType="submit"
							block
							className="login-button"
						>
							登录
						</Button>
					</Form.Item>
				</Form>
			</Modal>
		</>
	)
}

export default LoginModal
